package com.atguigu.yygh.user.service.impl;

import cn.hutool.core.lang.Validator;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCode;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.enums.UserStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-12-27
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户认证
     *
     * @param userId
     * @param userAuthVo
     */
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {

        //设置认证信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        //信息更新
        baseMapper.updateById(userInfo);
    }

    /**
     * 用户锁定和解锁
     *
     * @param userId
     * @param status
     */
    @Override
    public boolean lock(Long userId, Integer status) {
        if (status == 0 || status == 1) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setStatus(status);
            return this.updateById(userInfo);
        }
        return false;
    }

    @Autowired
    private PatientService patientService;

    /**
     * 认证审批  2通过  -1不通过
     *
     * @param userId
     * @param authStatus
     * @return
     */
    @Override
    public boolean approval(Long userId, Integer authStatus) {
        if (authStatus == AuthStatusEnum.AUTH_SUCCESS.getStatus()
                || authStatus == AuthStatusEnum.AUTH_FAIL.getStatus()) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setAuthStatus(authStatus);
            return this.updateById(userInfo);
        }
        return false;
    }

    /**
     * 查询用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String, Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo", userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllByUserId(userId);
        map.put("patientList", patientList);
        return map;
    }

    /**
     * 分页条件查询
     *
     * @param pageParam
     * @param userInfoQueryVo
     * @return
     */
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {

        //UserInfoQueryVo获取条件值
        String keyword = userInfoQueryVo.getKeyword(); //用户名称
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();

        wrapper.and(!StringUtils.isEmpty(keyword),
                        i -> i.like("name", keyword)
                                .or()
                                .like("phone", keyword))
                .ge(!StringUtils.isEmpty(createTimeBegin), "create_time", createTimeBegin)
                .le(!StringUtils.isEmpty(createTimeEnd), "create_time", createTimeEnd);

        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(this::packageUserInfo);
        return pages;
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        return userInfo;
    }

    @Override
    public UserInfo getUserInfoById(Long userId) {
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        return userInfo;
    }

    @Override
    public UserInfo getUserInfo(Gson gson, String openid, String accessToken) throws Exception {
        UserInfo userInfo;
        //向微信的资源服务器发起请求，获取当前用户的用户信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + accessToken +
                "&openid=" + openid;

        //使用httpclient发送请求
        String userInfoResult = HttpClientUtils.get(userInfoUrl);
        log.info("userInfoResult：" + userInfoResult);

        HashMap userInfoResultMap = gson.fromJson(userInfoResult, HashMap.class);
        //判断失败的响应
        if (userInfoResultMap.get("errcode") != null) {
            throw new YyghException(20017, "获取用户信息失败");
        }

        //解析用户信息 TODO 优化到service中
        String nickname = (String) userInfoResultMap.get("nickname");
        //用户注册
        userInfo = new UserInfo();
        userInfo.setOpenid(openid);
        userInfo.setNickName(nickname);
        userInfo.setName(nickname);
        userInfo.setStatus(UserStatusEnum.NORMAL.getStatus());
        this.save(userInfo);
        return userInfo;
    }

    @Override
    public UserInfo selectWxInfoByOpenId(String openid) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        // TODO 校对验证码是否正确
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        Object redisCode = redisTemplate.opsForValue().get("code:" + phone);
        if (redisCode instanceof String) {
            if (!code.equals(redisCode)) {
                throw new YyghException(ResultCodeEnum.VERIFICATION_CODE_ERROR);
            }
        }

        //校验参数
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PHONE_NUMBER_IS_EMPTY);
        }
        // 正则校验手机号是否正确 /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        boolean isMobile = Validator.isMobile(phone);
        if (!isMobile) {
            throw new YyghException(ResultCodeEnum.LOGIN_MOBILE_ERROR);
        }

        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(openid)) {
            log.info("登录");
            // 根据手机号查找会员是否存在
            UserInfo userInfo = getUserInfoByPhone(phone);
            //校验是否被禁用
            if (userInfo != null && userInfo.getStatus() == 0) {
                throw new YyghException(20001, "用户已经禁用");
            }

            if (userInfo != null && userInfo.getStatus().equals(UserStatusEnum.LOCK.getStatus())) {
                throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
            }
            // 不存在：未注册
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setName(phone); // 实名认证暂时用phone代替
                userInfo.setNickName(phone);
                userInfo.setStatus(UserStatusEnum.NORMAL.getStatus());
                baseMapper.insert(userInfo);
            }

            // 存在：已注册
            // 生成访问令牌 TODO
            userInfo = getUserInfoByPhone(phone); // 第一次注册为空
            String token = JwtHelper.createToken(Objects.requireNonNull(userInfo).getId(), userInfo.getName());
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", Objects.requireNonNull(userInfo).getName());
            map.put("token", token); // 访问令牌

            return map;
        } else { // 绑定手机号
            log.info("绑定手机号");
            UserInfo userInfo = getUserInfoByPhone(phone);

            if (userInfo != null) {
                throw new YyghException(ResultCode.ERROR, "手机号已绑定");
            }
            //数据库不存在相同绑定手机号
            //根据openid获取微信信息
            userInfo = this.selectWxInfoByOpenId(openid);
            //设置绑定手机号
            userInfo.setPhone(phone);
            //更新
            baseMapper.updateById(userInfo);
            //返回页面显示名称
            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();
            //jwt生成token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("name", name);
            map.put("token", token); //访问令牌
            return map;
        }


    }

    private UserInfo getUserInfoByPhone(String phone) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo;
    }


}
